package com.example.demo.config;

import com.example.demo.interceptor.MyAccessDeniedHandler;
import com.example.demo.interceptor.MyExceptionInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Mr.Xi
 * Date: 2023-04-24
 * Time: 20:09
 */

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)   // 开启权限注解使用
public class SecurityConfig {
    @Autowired
    private JWTAuthenticationFilter jwtAuthenticationFilter;

    @Autowired
    private MyExceptionInterceptor myExceptionInterceptor;

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/home/login").anonymous()
                .anyRequest().authenticated();

        // 添加 JWT 过滤器
        http
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        // 实现 认证 和 授权 异常处理器
        http
                .exceptionHandling()
                .authenticationEntryPoint(myExceptionInterceptor)
                .accessDeniedHandler(myAccessDeniedHandler);
        // SpringSecurity 配置跨域允许
        http
                .cors();

        return http.build();
    }
}
